package com.bvr;


import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class PropertyObjectAdapter extends ArrayAdapter<PropertyObject> {

	private ArrayList<PropertyObject> items;

	public PropertyObjectAdapter(Context context, int textViewResourceId,
			ArrayList<PropertyObject> items) {
		super(context, textViewResourceId, items);
		this.items = items;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);

			v = vi.inflate(R.layout.property_row, null);
		}
		PropertyObject o = items.get(position);
		if (o != null) {

			TextView lblTitle = (TextView) v.findViewById(R.id.propertyTitle);
			TextView lblDesc = (TextView) v.findViewById(R.id.propertyDesc);
			TextView lblRate = (TextView) v.findViewById(R.id.propertyRate);
			ImageView imgProperty = (ImageView) v
					.findViewById(R.id.imgProperty);

			if (lblTitle != null) {
				lblTitle.setText(o.getTitle());
			}
			if (lblDesc != null) {
				lblDesc.setText(o.getDesc());
			}
			if (lblRate != null) {
				lblRate.setText("Rate: " + o.getRate());
			}

			if (imgProperty != null) {
				Drawable drawable = LoadImageFromWebOperations(o.getImage());
				if(drawable != null) {
				imgProperty.setImageDrawable(drawable);
				}
				else {
				imgProperty.setImageResource(R.drawable.no_image);
				}
				
			}

		}
		return v;
	}

	private Drawable LoadImageFromWebOperations(String url) {
		try {
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is, "src name");
			return d;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return null;
		}
	}

}
